package com.ct.gd.passport.view.ticket;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import com.ct.gd.passport.R;
import com.ct.gd.passport.common.BaseActivity;
import com.ct.gd.passport.domain.TicketBookingInfo;
import com.ct.gd.passport.domain.TicketInfo;
import com.ct.gd.passport.view.BundleKeys;
import com.ct.gd.passport.view.InputInvalidException;
import com.ct.gd.passport.view.consult.SubmitActivity;
import com.ct.gd.passport.view.widget.AlwaysFireSpinner;
import com.ct.gd.passport.view.widget.CustomHeaderFragment;
import com.up91.common.android.async.ILoading;
import com.up91.common.android.async.SimpleAsyncTask;
import com.up91.common.android.helper.ToastHelper;
import org.apache.commons.lang3.StringUtils;

public class TicketBookingActivity extends BaseActivity implements AdapterView.OnItemSelectedListener, View.OnClickListener {

    private AlwaysFireSpinner mSpType;
    private EditText mEdtName;
    private EditText mEdtPhone;
    private EditText mEdtAdultCount;
    private EditText mEdtChildCount;
    private Button mBtnSubmit;

    private String serial;
    private View mViewTicketInfo;

    @Override
    protected void onBaseCreate(Bundle savedInstanceState) {
        setContentView(R.layout.ticket_booking_form);
    }

    @Override
    protected void initViews() {
        CustomHeaderFragment header = (CustomHeaderFragment) getFragmentManager().findFragmentById(R.id.header);
        header.setCenterText(R.string.ticket_booking);

        mSpType = (AlwaysFireSpinner) findViewById(R.id.ticket_booking_type_spin);
        mSpType.setOnItemSelectedEvenIfUnchangedListener(this);
        mBtnSubmit = (Button) findViewById(R.id.ticket_booking_submit_btn);
        mBtnSubmit.setOnClickListener(this);

        mEdtName = (EditText) findViewById(R.id.ticket_booking_name_edt);
        mEdtPhone = (EditText) findViewById(R.id.ticket_booking_phone_edt);
        mEdtAdultCount = (EditText) findViewById(R.id.ticket_booking_adult_edt);
        mEdtChildCount = (EditText) findViewById(R.id.ticket_booking_child_edt);

        mViewTicketInfo = findViewById(R.id.ticket_info_area);
        mViewTicketInfo.setOnClickListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (position > 0) {
            Intent intent = new Intent(this, TicketInfoActivity.class);
            intent.putExtra(BundleKeys.TICKET_TYPE, position);
            startActivityForResult(intent, 0);
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null != data) {
            TicketInfo info = (TicketInfo) data.getSerializableExtra(BundleKeys.TICKET_INFO);
            serial = info.serial;
            updateTicketInfo(info);
        }
    }

    private void updateTicketInfo(TicketInfo info) {
        mViewTicketInfo.setVisibility(View.VISIBLE);

        TextView tvSerial = (TextView) findViewById(R.id.ticket_info_serial_tv);
        TextView tvTerminal = (TextView) findViewById(R.id.ticket_info_terminal_tv);
        TextView tvComment = (TextView) findViewById(R.id.ticket_info_comment_tv);
        TableLayout table = (TableLayout) findViewById(R.id.ticket_info_start_info_area);
        TicketInfoFragment.setContent(info, tvSerial, tvTerminal, tvComment, table);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ticket_booking_submit_btn:
                submit();
                break;
        }
    }

    private void submit() {
        TicketBookingInfo t = null;
        try {
            t = render();
            new SubmitTask(this, true).execute(t);
        } catch (InputInvalidException e) {
            ToastHelper.toast(this, e.getMessage());
            View input = e.getInput();
            if (null != input) input.requestFocus();
        }
    }

    private TicketBookingInfo render() throws InputInvalidException {
        if (StringUtils.isEmpty(serial)) {
            throw new InputInvalidException(R.string.ticket_booking_serial_empty, mSpType);
        }

        String name = mEdtName.getText().toString().trim();
        if (StringUtils.isEmpty(name)) {
            throw new InputInvalidException(R.string.ticket_booking_name_empty, mEdtName);
        }
        String phone = mEdtPhone.getText().toString().trim();
        if (StringUtils.isEmpty(phone)) {
            throw new InputInvalidException(R.string.ticket_booking_phone_empty, mEdtPhone);
        }
        String adultCountStr = mEdtAdultCount.getText().toString().trim();
        String childCountStr = mEdtChildCount.getText().toString().trim();

        int adultCount;
        try {
            adultCount = new Integer(adultCountStr);
        } catch (NumberFormatException e) {
            throw new InputInvalidException(R.string.ticket_booking_adult_count, mEdtAdultCount);
        }

        int childCount;
        try {
            childCount = new Integer(childCountStr);
        } catch (NumberFormatException e) {
            throw new InputInvalidException(R.string.ticket_booking_child_count, mEdtChildCount);
        }

        TicketBookingInfo t = new TicketBookingInfo();
        t.serial = serial;
        t.name = name;
        t.phone = phone;
        t.adultCount = adultCount;
        t.childCount = childCount;
        return t;
    }

    private class SubmitTask extends SimpleAsyncTask<TicketBookingInfo, Void, Boolean> {

        public SubmitTask(ILoading loading, boolean showLoading) {
            super(loading, showLoading);
        }

        @Override
        protected Boolean onLoad(TicketBookingInfo... params) throws Exception {
            return params[0].submit();
        }

        @Override
        protected void onUI(Boolean aBoolean) {
//            ToastHelper.toast(getBaseContext(), R.string.ticket_booking_submit_succ);
            AlertDialog.Builder dialog = new AlertDialog.Builder(TicketBookingActivity.this).setTitle(R.string.success).setMessage(R.string.ticket_booking_submit_succ);
            dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    TicketBookingActivity.this.finish();
                }
            });
            dialog.show();
//            finish();
        }

        @Override
        protected void onHandleError(String errorMsg) {
            ToastHelper.toast(getBaseContext(), R.string.ticket_booking_submit_fail);
        }
    }
}